// 全局变量
let orderList = [];
let currentFilter = '全部订单';
let currentDateRange = 'all';
let currentPage = 1;
const pageSize = 5; // 每页显示订单数

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 加载公共头部
    // loadHeader();
    
    // 初始化页面
    initPage();
    
    // 绑定事件
    bindEvents();
});

// 加载头部
// function loadHeader() {
//     fetch('./header.html')
//         .then(response => response.text())
//         .then(data => {
//             document.getElementById('commonHeader').innerHTML = data;
//             if (window.updateHeaderUI) {
//                 window.updateHeaderUI();
//             }
//         });
// }

// 初始化页面
function initPage() {
    // 检查用户是否登录
    const token = localStorage.getItem('token');
    if (!token) {
        // 未登录，跳转到登录页
        window.location.href = './login.html?redirect=' + encodeURIComponent(window.location.href);
        return;
    }
    
    // 加载订单数据
    loadOrderData();
}

// 加载订单数据
function loadOrderData() {
    layui.use('layer', function() {
        const layer = layui.layer;
        const loadingIndex = layer.load(2);
        
        ApiService.order.getOrders()
            .then(response => {
                layer.close(loadingIndex);
                
                if (response.data) {
                    orderList = response.data;
                    
                    // 更新订单数量显示
                    updateOrderCounts();
                    
                    // 应用筛选
                    applyFilters();
                } else {
                    orderList = [];
                    renderEmptyOrders();
                }
            })
            .catch(error => {
                layer.close(loadingIndex);
                console.error("获取订单数据失败:", error);
                layer.msg('获取订单数据失败，请重试', {icon: 2});
                renderEmptyOrders();
            });
    });
}

// 更新订单数量显示
function updateOrderCounts() {
    // 计算各状态订单数量
    const counts = {
        '全部订单': orderList.length,
        '待付款': orderList.filter(order => order.status === '待付款').length,
        '待发货': orderList.filter(order => order.status === '待发货').length,
        '待收货': orderList.filter(order => order.status === '待收货').length,
        '已完成': orderList.filter(order => order.status === '已完成').length,
        '已取消': orderList.filter(order => order.status === '已取消').length
    };
    
    // 更新UI显示
    document.querySelectorAll('.filter-item').forEach(item => {
        const statusText = item.querySelector('span').textContent.trim();
        const countElement = item.querySelector('.count, .badge');
        
        if (countElement && counts[statusText] !== undefined) {
            countElement.textContent = counts[statusText];
        }
    });
}

// 应用筛选
function applyFilters() {
    // 获取符合条件的订单
    let filteredOrders = orderList;
    
    // 状态筛选
    if (currentFilter !== '全部订单') {
        const statusMap = {
            '待付款': '待付款',
            '待发货': '待发货',
            '待收货': '待收货',
            '已完成': '已完成',
            '已取消': '已取消'
        };
        
        filteredOrders = filteredOrders.filter(order => order.status === statusMap[currentFilter]);
    }
    
    // 日期筛选
    if (currentDateRange !== 'all') {
        const now = new Date();
        let daysLimit;
        
        switch(currentDateRange) {
            case '一个月内':
                daysLimit = 30;
                break;
            case '三个月内':
                daysLimit = 90;
                break;
            case '半年内':
                daysLimit = 180;
                break;
            case '一年内':
                daysLimit = 365;
                break;
            default:
                daysLimit = null;
        }
        
        if (daysLimit) {
            filteredOrders = filteredOrders.filter(order => {
                const orderDate = new Date(order.createdAt);
                const daysDiff = Math.floor((now - orderDate) / (1000 * 60 * 60 * 24));
                return daysDiff <= daysLimit;
            });
        }
    }
    
    // 分页处理
    const totalPages = Math.ceil(filteredOrders.length / pageSize);
    currentPage = Math.min(currentPage, totalPages || 1);
    
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pageOrders = filteredOrders.slice(startIndex, endIndex);
    
    // 渲染订单列表
    renderOrders(pageOrders);
    
    // 渲染分页
    renderPagination(totalPages);
}

// 渲染订单列表
function renderOrders(orders) {
    const orderListContainer = document.querySelector('.order-list');
    
    if (orders.length === 0) {
        orderListContainer.innerHTML = `
            <div class="empty-orders">
                <p>暂无相关订单</p>
            </div>
        `;
        return;
    }
    
    orderListContainer.innerHTML = orders.map(order => {
        // 订单状态显示
        const statusClass = getStatusClass(order.status);
        const statusText = getStatusText(order.status);
        
        // 订单商品列表
        const productList = order.items.map(item => `
            <div class="product-item">
                <img src="${item.imageUrl || './img/default-book.jpg'}" alt="${item.bookTitle}">
                <div class="product-info">
                    <h3>${item.bookTitle}</h3>
                    <p class="author">${item.bookAuthor || '未知作者'}</p>
                    <div class="book-attrs">
                        <span>${item.bookDegree || '全新'}</span>
                    </div>
                    <div class="price-info">
                        <span class="price">¥${item.price.toFixed(2)}</span>
                        <span class="count">x${item.quantity}</span>
                    </div>
                </div>
            </div>
        `).join('');
        
        // 订单底部按钮
        const actionButtons = getActionButtons(order);
        
        // 倒计时显示（仅待付款订单）
        const countdownHtml = order.status === '待付款' ? 
            `<div class="countdown" data-order-id="${order.id}">支付剩余时间：${formatCountdown(order.expireTime)}</div>` : '';
        
        return `
            <div class="order-item" data-id="${order.id}">
                <div class="order-header">
                    <div class="order-meta">
                        <span class="order-date">${formatDate(order.createdAt)}</span>
                        <span class="order-number">订单号：${order.orderNumber}</span>
                    </div>
                    <div class="order-status ${statusClass}">${statusText}</div>
                </div>

                <div class="order-content">
                    <div class="product-list">
                        ${productList}
                    </div>
                </div>

                <div class="order-footer">
                    <div class="total-info">
                        <span>共${order.totalQuantity}件商品</span>
                        <span class="divider">|</span>
                        <span>实付款：</span>
                        <span class="total-price">¥${order.totalAmount.toFixed(2)}</span>
                        <span class="divider">|</span>
                        <span class="delivery-info">${order.deliveryFee > 0 ? `运费：¥${order.deliveryFee.toFixed(2)}` : '包邮'}</span>
                    </div>
                    ${countdownHtml}
                    <div class="order-actions">
                        ${actionButtons}
                    </div>
                </div>
            </div>
        `;
    }).join('');
    
    // 启动倒计时
    startCountdowns();
}

// 启动倒计时
function startCountdowns() {
    const countdowns = document.querySelectorAll('.countdown');
    
    // 清除现有的倒计时定时器
    if (window.countdownTimer) {
        clearInterval(window.countdownTimer);
    }
    
    if (countdowns.length === 0) {
        return;
    }
    
    // 创建新的倒计时定时器
    window.countdownTimer = setInterval(() => {
        countdowns.forEach(countdown => {
            const orderId = countdown.getAttribute('data-order-id');
            const order = orderList.find(o => o.id == orderId);
            
            if (order && order.expireTime) {
                const countdownText = formatCountdown(order.expireTime);
                countdown.textContent = `支付剩余时间：${countdownText}`;
                
                // 如果已过期，刷新页面
                if (countdownText === '已过期') {
                    loadOrderData();
                }
            }
        });
    }, 1000);
}

// 获取订单状态样式类
function getStatusClass(status) {
    switch(status) {
        case '待付款': return 'pending';
        case '已付款': return 'shipped';
        case '待发货': return 'shipped';
        case '已完成': return 'completed';
        case '已取消': return 'cancelled';
        default: return '';
    }
}

// 获取订单状态文本
function getStatusText(status) {
    // switch(status) {
    //     case '待付款': return '待付款';
    //     case '已付款': return '待发货';
    //     case '待发货': return '待收货';
    //     case '已完成': return '已完成';
    //     case '已取消': return '已取消';
    //     default: return '未知状态';
    // }
    return status;
}

// 获取订单操作按钮
function getActionButtons(order) {
    switch(order.status) {
        case '待付款':
            return `
                <button class="btn-default" onclick="cancelOrder(${order.id})">取消订单</button>
                <button class="btn-primary" onclick="payOrder(${order.id})">立即付款</button>
            `;
        case '已付款':
            return `
                <button class="btn-default" onclick="viewOrderDetail(${order.id})">查看详情</button>
                <button class="btn-primary" onclick="remindShipping(${order.id})">提醒发货</button>
            `;
        case '待发货':
            return `
                <button class="btn-default" onclick="viewLogistics(${order.id})">查看物流</button>
                <button class="btn-primary" onclick="confirmReceive(${order.id})">确认收货</button>
            `;
        case '已完成':
            return `
                <button class="btn-default" onclick="viewLogistics(${order.id})">查看物流</button>
                <button class="btn-default" onclick="deleteOrder(${order.id})">删除订单</button>
                <button class="btn-primary" onclick="buyAgain(${order.id})">再次购买</button>
            `;
        case '已取消':
            return `
                <button class="btn-default" onclick="deleteOrder(${order.id})">删除订单</button>
                <button class="btn-primary" onclick="buyAgain(${order.id})">再次购买</button>
            `;
        default:
            return `<button class="btn-default" onclick="viewOrderDetail(${order.id})">查看详情</button>`;
    }
}

// 渲染分页
function renderPagination(totalPages) {
    const paginationContainer = document.querySelector('.pagination');
    
    if (totalPages <= 1) {
        paginationContainer.style.display = 'none';
        return;
    }
    
    paginationContainer.style.display = 'flex';
    
    let paginationHtml = '';
    
    // 显示页码按钮
    for (let i = 1; i <= totalPages; i++) {
        if (i === currentPage) {
            paginationHtml += `<button class="page-btn active">${i}</button>`;
        } else {
            paginationHtml += `<button class="page-btn" onclick="goToPage(${i})">${i}</button>`;
        }
    }
    
    paginationContainer.innerHTML = paginationHtml;
}

// 跳转到指定页
function goToPage(page) {
    currentPage = page;
    applyFilters();
    
    // 滚动到页面顶部
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
}

// 渲染空订单
function renderEmptyOrders() {
    const orderListContainer = document.querySelector('.order-list');
    
    orderListContainer.innerHTML = `
        <div class="empty-orders">
            <img src="./img/empty-order.png" alt="暂无订单">
            <p>暂无订单记录</p>
            <a href="./catalog.html" class="btn-primary">去购物</a>
        </div>
    `;
    
    // 隐藏分页
    document.querySelector('.pagination').style.display = 'none';
}

// 绑定事件
function bindEvents() {
    // 状态筛选
    document.querySelectorAll('.filter-item').forEach(item => {
        item.addEventListener('click', function() {
            // 更新激活状态
            document.querySelectorAll('.filter-item').forEach(i => i.classList.remove('active'));
            this.classList.add('active');
            
            // 更新当前筛选条件
            currentFilter = this.querySelector('span').textContent.trim();
            currentPage = 1;
            
            // 应用筛选
            applyFilters();
        });
    });
    
    // 日期筛选
    const dateSelect = document.querySelector('.date-filter select');
    if (dateSelect) {
        dateSelect.addEventListener('change', function() {
            currentDateRange = this.value;
            currentPage = 1;
            applyFilters();
        });
    }
    
    // 搜索功能
    const searchBtn = document.querySelector('.search-btn');
    const searchInput = document.querySelector('.search-box input');
    
    if (searchBtn && searchInput) {
        searchBtn.addEventListener('click', function() {
            searchOrders();
        });
        
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchOrders();
            }
        });
    }
}

// 搜索订单
function searchOrders() {
    const searchInput = document.querySelector('.search-box input');
    const keyword = searchInput.value.trim().toLowerCase();
    
    if (!keyword) {
        loadOrderData(); // 如果关键词为空，重新加载所有订单
        return;
    }
    
    // 在原始订单列表中搜索
    const searchResults = orderList.filter(order => {
        // 搜索订单号
        if (order.orderNumber.toLowerCase().includes(keyword)) {
            return true;
        }
        
        // 搜索商品名称
        return order.items.some(item => 
            item.book.title.toLowerCase().includes(keyword)
        );
    });
    
    // 更新筛选结果
    currentFilter = '全部订单';
    currentPage = 1;
    
    // 更新UI状态
    document.querySelectorAll('.filter-item').forEach(item => {
        item.classList.remove('active');
        if (item.querySelector('span').textContent.trim() === '全部订单') {
            item.classList.add('active');
        }
    });
    
    // 渲染搜索结果
    if (searchResults.length > 0) {
        const totalPages = Math.ceil(searchResults.length / pageSize);
        const pageOrders = searchResults.slice(0, pageSize);
        
        renderOrders(pageOrders);
        renderPagination(totalPages);
    } else {
        const orderListContainer = document.querySelector('.order-list');
        orderListContainer.innerHTML = `
            <div class="empty-orders">
                <img src="./img/empty-order.png" alt="暂无订单">
                <p>未找到与"${keyword}"相关的订单</p>
            </div>
        `;
        
        document.querySelector('.pagination').style.display = 'none';
    }
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 格式化倒计时
function formatCountdown(expireTimeString) {
    // 检查是否有有效的过期时间
    if (!expireTimeString) {
        // 默认设置为1小时倒计时
        return '01:00:00';
    }
    
    let expireTime;
    
    // 尝试解析日期字符串
    try {
        // 如果是时间戳（数字字符串）
        if (!isNaN(Number(expireTimeString))) {
            expireTime = new Date(Number(expireTimeString));
        } else {
            // 否则作为日期字符串解析
            expireTime = new Date(expireTimeString);
        }
        
        // 检查解析后的日期是否有效
        if (isNaN(expireTime.getTime())) {
            console.error('无效的过期时间格式:', expireTimeString);
            // 默认设置为1小时倒计时
            return '01:00:00';
        }
    } catch (error) {
        console.error('解析过期时间出错:', error);
        // 默认设置为1小时倒计时
        return '01:00:00';
    }
    
    const now = new Date();
    
    // 计算剩余时间（毫秒）
    let remainingTime = expireTime - now;
    
    if (remainingTime <= 0) {
        return '已过期';
    }
    
    // 转换为时分秒
    const hours = Math.floor(remainingTime / (1000 * 60 * 60));
    remainingTime %= (1000 * 60 * 60);
    
    const minutes = Math.floor(remainingTime / (1000 * 60));
    remainingTime %= (1000 * 60);
    
    const seconds = Math.floor(remainingTime / 1000);
    
    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}

// 取消订单
function cancelOrder(orderId) {
    layui.use('layer', function() {
        const layer = layui.layer;
        
        layer.confirm('确定要取消该订单吗？', {icon: 3, title:'提示'}, function(index){
            const loadingIndex = layer.load(2);
            
            ApiService.order.cancelOrder(orderId)
                .then(response => {
                    layer.close(loadingIndex);
                    
                    if (response.data) {
                        layer.msg('订单已取消', {icon: 1});
                        
                        loadOrderData()
                        // 更新本地数据
                        const order = orderList.find(o => o.id === orderId);
                        if (order) {
                            order.status = '已取消';
                            applyFilters();
                        }
                    }
                })
                .catch(error => {
                    layer.close(loadingIndex);
                    console.error("取消订单失败:", error);
                    layer.msg('取消订单失败，请重试', {icon: 2});
                });
            
            layer.close(index);
        });
    });
}

// 支付订单
function payOrder(orderId) {
    // 跳转到支付页面
    window.location.href = `./payment.html?orderId=${orderId}`;
}

// 查看订单详情
function viewOrderDetail(orderId) {
    window.location.href = `./order-detail.html?id=${orderId}`;
}

// 提醒发货
function remindShipping(orderId) {
    layui.use('layer', function() {
        const layer = layui.layer;
        layer.msg('已提醒卖家尽快发货', {icon: 1});
    });
}

// 查看物流
function viewLogistics(orderId) {
    layui.use('layer', function() {
        const layer = layui.layer;
        
        // 获取物流信息
        ApiService.order.getOrderLogistics(orderId)
            .then(response => {
                if (response.data) {
                    // 显示物流信息弹窗
                    layer.open({
                        type: 1,
                        title: '物流信息',
                        area: ['500px', '400px'],
                        content: generateLogisticsHtml(response.data)
                    });
                } else {
                    layer.msg('暂无物流信息', {icon: 0});
                }
            })
            .catch(error => {
                console.error("获取物流信息失败:", error);
                layer.msg('获取物流信息失败，请重试', {icon: 2});
            });
    });
}

// 生成物流信息HTML
function generateLogisticsHtml(logistics) {
    if (!logistics.traces || logistics.traces.length === 0) {
        return '<div class="logistics-empty">暂无物流信息</div>';
    }
    
    const tracesHtml = logistics.traces.map(trace => `
        <div class="logistics-item">
            <div class="logistics-time">${formatDate(trace.time)}</div>
            <div class="logistics-info">${trace.content}</div>
        </div>
    `).join('');
    
    return `
        <div class="logistics-container">
            <div class="logistics-header">
                <div>物流公司：${logistics.company}</div>
                <div>运单号码：${logistics.number}</div>
            </div>
            <div class="logistics-timeline">
                ${tracesHtml}
            </div>
        </div>
    `;
}

// 确认收货
function confirmReceive(orderId) {
    layui.use('layer', function() {
        const layer = layui.layer;
        
        layer.confirm('确认已收到商品？', {icon: 3, title:'提示'}, function(index){
            const loadingIndex = layer.load(2);
            
            ApiService.order.confirmReceive(orderId)
                .then(response => {
                    layer.close(loadingIndex);
                    
                    if (response.data) {
                        layer.msg('确认收货成功', {icon: 1});
                        
                        loadOrderData()
                        // 更新本地数据
                        const order = orderList.find(o => o.id === orderId);
                        if (order) {
                            order.status = '已完成';
                            applyFilters();
                        }
                    }
                })
                .catch(error => {
                    layer.close(loadingIndex);
                    console.error("确认收货失败:", error);
                    layer.msg('确认收货失败，请重试', {icon: 2});
                });
            
            layer.close(index);
        });
    });
}

// 删除订单
function deleteOrder(orderId) {
    layui.use('layer', function() {
        const layer = layui.layer;
        
        layer.confirm('确定要删除该订单吗？删除后将无法恢复。', {icon: 3, title:'提示'}, function(index){
            const loadingIndex = layer.load(2);
            
            ApiService.order.deleteOrder(orderId)
                .then(response => {
                    layer.close(loadingIndex);
                    
                    if (response.data) {
                        layer.msg('订单已删除', {icon: 1});
                        
                        loadOrderData()
                        // 从本地数据中删除
                        orderList = orderList.filter(o => o.id !== orderId);
                        applyFilters();
                    }
                })
                .catch(error => {
                    layer.close(loadingIndex);
                    console.error("删除订单失败:", error);
                    layer.msg('删除订单失败，请重试', {icon: 2});
                });
            
            layer.close(index);
        });
    });
}

// 再次购买
function buyAgain(orderId) {
    const order = orderList.find(o => o.id === orderId);
    
    if (!order) {
        layui.use('layer', function() {
            const layer = layui.layer;
            layer.msg('订单信息不存在', {icon: 2});
        });
        return;
    }
    
    // 将商品添加到购物车
    const addPromises = order.items.map(item => 
        ApiService.cart.addToCart(item.book.id, item.quantity)
    );
    
    layui.use('layer', function() {
        const layer = layui.layer;
        const loadingIndex = layer.load(2);
        
        Promise.all(addPromises)
            .then(() => {
                layer.close(loadingIndex);
                layer.msg('已添加到购物车', {icon: 1});
                
                // 更新购物车数量
                if (AuthService.updateCartCount) {
                    AuthService.updateCartCount();
                }
                
                // 询问是否前往购物车
                layer.confirm('商品已添加到购物车，是否立即结算？', {icon: 1, title:'提示'}, function(index){
                    window.location.href = './cart.html';
                    layer.close(index);
                });
            })
            .catch(error => {
                layer.close(loadingIndex);
                console.error("添加到购物车失败:", error);
                layer.msg('添加到购物车失败，请重试', {icon: 2});
            });
    });
}